<template>
  <div class="content">
    <div class="subject-title">
      <span>主题名称：{{ subjectData.subjectName }}</span>
      <span>主题编码：{{ subjectData.subjectCode }}</span>
    </div>
    <el-form :model="includedServiceQueryParams" ref="queryForm" :inline="true">
      <el-form-item label="事项名称" prop="serviceName">
        <el-input
          v-model="includedServiceQueryParams.serviceName"
          placeholder="请输入事项名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事项编码" prop="serviceCode">
        <el-input
          v-model="includedServiceQueryParams.serviceCode"
          placeholder="请输入事项编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <template v-if="type !== '0'">
        <el-col :span="1.5" >
          <el-button
            type="success"
            icon="el-icon-plus"
            size="mini"
            :disabled="!includedServiceQueryParams.subjectCode"
            v-hasPermi="['items:subject:batchAddServiceSubject']"
            @click="handleAddSubjectService"
          >增加主题关联事项
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="checkedServiceCodes.length === 0"
            @click="handleDelete"
            v-hasPermi="['item:subject:removeServiceSubject']"
          >删除
          </el-button>
        </el-col>
      </template>

      <el-col :span="1.5" style="float: right">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getIncludedServiceList"/>
        </el-tooltip>
      </el-col>

    </el-row>
    <el-table
      v-loading="listLoading"
      :data="includedServiceList"
      @selection-change="includedServiceListSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="事项名称" align="center" prop="serviceName"/>
      <el-table-column label="事项编码" width="190" align="center" prop="serviceCode"/>
      <el-table-column label="事项类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ typeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="实施部门编码" align="center" prop="deptCode"/>
      <el-table-column label="实施部门名称" align="center" prop="deptName"/>
      <el-table-column label="排序号" align="center" prop="sort" width="80px"/>
      <el-table-column label="是否已启用" align="center" prop="sort" width="100px">
        <template slot-scope="scope">
          {{ scope.row.enable === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" >
          <el-button
            v-if="type !== '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditSort(scope.row)"
            v-hasPermi="['item:subject:editServiceSubject']"
          >修改排序号
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="navToServicePage(scope.row)"
            v-hasPermi="['items:service:list']"
          >查看
          </el-button>
          <el-button
            v-if="type !== '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['item:subject:removeServiceSubject']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="includedServiceTotal>0"
      :total="includedServiceTotal"
      :page.sync="includedServiceQueryParams.pageNum"
      :limit="includedServiceQueryParams.pageSize"
      layout="total, prev, pager, next, jumper"
      @pagination="getIncludedServiceList"
    />

    <el-dialog
      :visible.sync="openAddServiceDialog"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
      @close="closeAddServiceDialogCallback"
    >
      <template slot="title">增加主题关联事项 【{{ subjectData.subjectName }}】</template>
      <div style="margin-bottom: 20px">
        <el-input
          v-model="addServiceQueryParams.serviceName"
          placeholder="请输入事项名称"
          clearable
          size="small"
          @keyup.enter.native="handleQueryCanAddService"
          style="width: 300px; margin-right: 10px"
        />
        <el-input
          v-model="addServiceQueryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQueryCanAddService"
          style="width: 300px; margin-right: 10px"
        />
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQueryCanAddService">搜索</el-button>
      </div>
      <el-table
        max-height="500px"
        v-loading="includedServiceDialogLoading"
        :data="canAddServiceList"
        @selection-change="handleAddServiceSelectionChange"
        ref="addAssociateServiceTable"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="事项名称" align="center" prop="serviceName"/>
        <el-table-column label="事项编码" align="center" prop="serviceCode"/>
        <el-table-column label="事项类型" align="center" prop="type">
          <template slot-scope="scope">
            {{ typeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="实施部门编码" align="center" prop="deptCode"/>
        <el-table-column label="实施部门名称" align="center" prop="deptName"/>
        <el-table-column label="排序号" align="center" prop="sort" width="140px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sort"
              size="small"
              :min="0"
              :precision="0"
              label="请输入排序号"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否已启用" align="center" prop="enable" width="100px">
          <template slot-scope="scope">
            {{ scope.row.enable === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="canAddServiceTotal>0"
        :total="canAddServiceTotal"
        :page.sync="addServiceQueryParams.pageNum"
        :limit="addServiceQueryParams.pageSize"
        layout="total, prev, pager, next, jumper"
        @pagination="handleAddServicePageChange"
      />
      <div slot="footer" class="dialog-footer">
        <div class="tip">
          注意：可选勾选多页多个事项一次性添加
        </div>
        <div class="right-wrap">
          <el-button type="primary" @click="handleSaveIncludedServices">确 定</el-button>
          <el-button @click="openAddServiceDialog = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <edit-sort-dialog
      :value="currentEditSortRow.sort || 0"
      :dialog-visible="openEditServiceSortDialog"
      @setDialogVisible="setDialogVisible"
      @sort-confirm="handleSortConfirm"
    />
  </div>
</template>

<script>
import {
  getListServiceSubject,
  getListExcludeSubject,
  batchAddServiceSubject,
  removeServiceSubject,
  editServiceSubject
} from "@/api/items/subject";
import EditSortDialog from "@/views/items/subject/components/EditSortDialog";
import {navTypeOptions} from "@/utils/dicts";

export default {
  name: "IncludeServices",
  components: {EditSortDialog},
  props: {
    subjectData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 主题包含事项多选框已选中行
      checkedServiceCodes: [],
      // 包含的事项列表
      includedServiceList: [],
      // 包含事项加载中
      listLoading: false,
      includedServiceTotal: 0,
      canAddServiceTotal: 0,
      // 是否展示包含事项弹窗
      openAddServiceDialog: false,
      includedServiceDialogLoading: false,
      // 获取当前主题包含的事项参数
      includedServiceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectCode: undefined,
        serviceName: undefined,
        serviceCode: undefined
      },
      // 获取可添加事项列表参数
      addServiceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectCode: undefined,
        branchCode: undefined,
        serviceName: undefined,
        deptName:undefined
      },
      // 增加可关联事项列表
      canAddServiceList: [],
      // 添加关联事项弹窗当前页选中事项
      currentPageSelectedList: [],
      // 缓存多个页所有已选中事项
      cacheAllPageSelectedServices: [],
      // 显示修改序号弹窗
      openEditServiceSortDialog: false,
      // 当前修改序号行数据
      currentEditSortRow: {},
      type: ''
    }
  },
  methods: {
    handleQuery(){
      this.includedServiceQueryParams.pageNum = 1;
      this.getIncludedServiceList();
    },
    // 事项类型文本
    typeLabel(value) {
      const item = navTypeOptions.find(item => {
        return item.value == value
      })
      return item ? item.label : null
    },
    // 确定修改排序号
    handleSortConfirm(value) {
      const params = {
        subjectCode: this.includedServiceQueryParams.subjectCode,
        sort: value,
        id: this.currentEditSortRow.id,
        serviceCode: this.currentEditSortRow.serviceCode
      };
      // 修改主题内事项排序号
      editServiceSubject(params).then(response => {
        this.openEditServiceSortDialog = false;
        // 重新获取列表
        this.getIncludedServiceList();
        this.$modal.msgSuccess("修改序号成功！");
      });
    },
    // 排序弹窗组件关闭
    setDialogVisible(boolean) {
      this.openEditServiceSortDialog = boolean;
    },
    // 修改序号
    handleEditSort(row) {
      // 记录当前修改序号行的数据
      this.currentEditSortRow = row;
      this.openEditServiceSortDialog = true;
    },
    navToServicePage(row) {
      this.$router.push({
        name: 'Service',
        query: {serviceCode: row.serviceCode}
      })
    },
    // 主题包含事项多选框改变
    includedServiceListSelectionChange(selection) {
      this.checkedServiceCodes = selection.map(item => item.serviceCode);
    },
    // 添加主题关联事项弹窗页数改变
    handleAddServicePageChange() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      // 重新获取数据
      this.getCanAddServiceList();
    },
    // 将选中项推入缓存列表，未选中的从缓存列表删除
    saveSelectedItemToCacheList() {
      // 保存当前页所有ids
      const currentPageIds = this.canAddServiceList.map(item => item.id);
      // 将当前页数据从缓存中删除，再将已选中的加入到缓存
      this.cacheAllPageSelectedServices = this.cacheAllPageSelectedServices.filter(item => {
        return !currentPageIds.includes(item.id)
      }).concat(this.currentPageSelectedList);

      // 清空当前页缓存
      this.currentPageSelectedList = [];
      // console.log("重新缓存数据", this.cacheAllPageSelectedServices);
    },

    // 关闭关联事项弹窗回调
    closeAddServiceDialogCallback() {
      // 关闭弹窗后清空选中缓存列表和选中列表
      this.cacheAllPageSelectedServices = [];
      this.currentPageSelectedList = [];
      this.canAddServiceList = [];
    },

    // 关联事项弹窗多选框选择改变
    handleAddServiceSelectionChange(selection) {
      // 当前页选中列表
      this.currentPageSelectedList = selection;
    },

    // 删除主题关联事项
    handleDelete(row) {
      const serviceCodes = row.serviceCode ? [row.serviceCode] : this.checkedServiceCodes;
      const params = serviceCodes.map(serviceCode => {
        return {
          serviceCode,
          subjectCode: this.includedServiceQueryParams.subjectCode
        }
      })
      this.$modal.confirm('是否确认删除选中的关联事项？').then(() => {
        return removeServiceSubject(params);
      }).then(() => {
        this.getIncludedServiceList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    // 保存关联事项
    handleSaveIncludedServices() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      // 如果没有选择事项提示选择
      if (!this.cacheAllPageSelectedServices.length) return this.$modal.msgWarning("请选择添加事项！");
      // 当前主题编码
      const subjectCode = this.includedServiceQueryParams.subjectCode;

      // 给每一个事项添加主题编码
      const params = this.cacheAllPageSelectedServices.map(item => {
        return {
          subjectCode,
          ...item,
        }
      })

      // 新增主题事项
      batchAddServiceSubject(params).then(response => {
        this.openAddServiceDialog = false;
        // 重新获取列表
        this.getIncludedServiceList();
        this.$modal.msgSuccess("添加成功！");
      });

    },

    // 增加关联事项搜索按钮
    handleQueryCanAddService() {
      // 缓存已选中事项信息
      this.saveSelectedItemToCacheList();
      this.addServiceQueryParams.pageNum = 1;
      this.getCanAddServiceList();
    },

    // 获取当前主题包含的事项
    getIncludedServiceList() {
      this.listLoading = true;
      // 获取该主题包含的事项
      getListServiceSubject(this.includedServiceQueryParams).then(response => {
        this.listLoading = false;
        this.includedServiceTotal = response.total;
        this.includedServiceList = response.rows;
      });
    },

    // 获取可增加关联事项列表
    getCanAddServiceList() {
      this.includedServiceDialogLoading = true;
      getListExcludeSubject(this.addServiceQueryParams).then(response => {
        this.includedServiceDialogLoading = false;
        this.canAddServiceTotal = response.total;
        this.canAddServiceList = response.rows.map(item => {
          const cacheItem = this.cacheAllPageSelectedServices.find(cacheItem => item.id === cacheItem.id);
          if(cacheItem){ // 存在缓存列表 自动回填序号
            item.sort = cacheItem.sort;
          }else{
            item.sort = 0;
          }
          return item
        });

        // 设置表格多选框默认选中
        this.$nextTick(() => {
          for (let i = 0; i < this.canAddServiceList.length; i++) {
            const row = this.canAddServiceList[i];
            if (this.cacheAllPageSelectedServices.some(item => row.serviceCode === item.serviceCode)) {
              this.$refs.addAssociateServiceTable.toggleRowSelection(row);
            }
          }
        })
      });
    },

    // 增加关联事项按钮
    handleAddSubjectService() {
      this.openAddServiceDialog = true;
      // 重置为第一页
      this.addServiceQueryParams.serviceName = undefined;
      this.addServiceQueryParams.deptName=undefined;
      this.addServiceQueryParams.pageNum = 1;
      this.getCanAddServiceList();
    },
  },
  watch: {
    subjectData: {
      immediate: true,
      handler(newValue) {
        // 存在id
        if (newValue.id) {
          this.addServiceQueryParams.subjectCode = newValue.subjectCode;
          this.addServiceQueryParams.branchCode = newValue.branchCode;
          this.includedServiceQueryParams.subjectCode = newValue.subjectCode;
          // 获取包含的事项
          this.getIncludedServiceList();
        }
      }
    },
  },
  mounted() {
    const {type} = this.$route.query;
    // 编辑类型 0：查看 1：修改 2：新增
    this.type = type;
  },
}
</script>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  width: 100%;
  height: 100%;

  .subject-title {
    word-break: break-word;
    margin-bottom: 10px;
    span{
      line-height: 30px;

      &:first-child{
        margin-right: 40px;
      }
    }
  }

}
.dialog-footer {
  position: relative;

  .tip {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 16px;
    line-height: 36px;
    color: red;
  }
}

</style>
